package com.sharp.core.raytrace;

import java.util.ArrayList;

import com.sharp.core.graphics.Light;
import com.sharp.core.math.primitives.Primitive;

public class BruteforceObjectHolder extends PrimitiveHolder {

	ArrayList<Light> lights;
	ArrayList<Primitive> list;
	
	public BruteforceObjectHolder() {
		list = new ArrayList<Primitive>();
		lights = new ArrayList<Light>();
	}
	
	@Override
	public void addObject(Primitive p) {
		list.add(p);
	}

	@Override
	public Intersection findIntersection(Ray r) {
		float min = Float.MAX_VALUE;
		Primitive prim = null;
		for ( Primitive p : list ) {
			float d = p.intersect(r);
			if ( d > 0 && d < min ) {
				min = d;
				prim = p;
			}
		}
		if ( prim == null )
			return null;
		Intersection inter = new Intersection(this);
		inter.setPos( r.getIntersectionVector(min) );
		inter.setPrimitive(prim);
		inter.setDistance(min);
		return inter;
	}
	
	@Override
	public boolean isIntersected(Ray ray) {
		for ( Primitive p : list ) {
			if ( p.isLight() )
				continue;
			float d = p.intersect(ray);
			if ( d > 0 ) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void addLight(Light p) {
		list.add(p);
		lights.add(p);
	}

	@Override
	public boolean isVisible(Intersection from, Light l) {
		Ray secondary = new Ray(from, l);
		return isIntersected(secondary) == false;
	}

	@Override
	public Iterable<Light> getLights() {
		return lights;
	}
}
